<template>
  <view class="container uv-safe-area-inset-bottom">
    <!-- 页面标题 -->
    <view class="header">
      <view class="header-content">
        <page-header title="规划网格" subtitle="合理布局规划网格明细" start-color="#39c5bb" end-color="#398dee" height="40rpx" />
      </view>
    </view>
    <!-- 级联选择区域 -->
    <view class="picker-area">
      <view class="picker-button" @click="showPicker">
        <text class="picker-text" v-if="selectedArea">{{ selectedArea + ' (' + total + ')' }}</text>
        <text class="picker-text" v-else>{{ '请选择区域' + ' (' + total + ')' }}</text>
        <view class="icon-area">
          <view v-if="selectedArea" @click.stop="resetList">
            <uv-icon name="close" size="20" color="#3c9cff"></uv-icon>
          </view>
          <uv-icon v-else name="arrow-down" size="20" color="#3c9cff"></uv-icon>
        </view>
      </view>
    </view>

    <!-- 关键字搜索区域 -->
    <view class="search-area">
      <uv-search
        v-model="secondaryGrid"
        placeholder="请输入网格名称或关键字"
        :clearabled="true"
        :show-action="true"
        action-text="搜索"
        @search="onSearch"
        @custom="onSearch"
        @clear="resetKeyword"
      ></uv-search>
    </view>

    <!-- 卡片列表区域 -->
    <view style="flex: 1; overflow: hidden">
      <scroll-view scroll-y class="scroll-view mt-5" @scrolltolower="loadMore">
        <!-- @refresherrefresh="onRefresh" -->
        <!-- <wd-status-tip v-if="guideList.length === 0" image="search" tip="暂无数据" /> -->
        <uv-empty v-if="guideList.length === 0" mode="list" text="暂无数据" icon="/static/empty-data.png"></uv-empty>
        <view class="card-list" v-else>
          <view class="card-item" v-for="(item, index) in guideList" :key="index" @click="viewDetail(item)">
            <view class="card-header">
              <text class="card-title">{{ item.secondaryGrid || '-' }}</text>
            </view>
            <view class="card-content">
              <view class="card-info-section">
                <view>
                  <view class="card-row">
                    <text class="card-label">一级网格：</text>
                    <text class="card-value">{{ item.primaryGrid || '一级网格' }}</text>
                  </view>
                  <view class="card-row">
                    <text class="card-label">网格属性：</text>
                    <text class="card-value">{{ item.gridAttributes || '-' }}</text>
                  </view>
                </view>
                <view class="card-tag" v-if="item.stockPrompt">
                  <uv-tags :text="item.stockPrompt" :type="getTagType(item.stockPrompt)" size="mini" shape="circle"></uv-tags>
                </view>
              </view>

              <view class="card-divider"></view>

              <view class="card-stats-section">
                <view class="card-stat-item">
                  <text class="stat-value">{{ item.licensedHouseholds || 0 }}</text>
                  <text class="stat-label">持证户数</text>
                </view>
                <view class="card-stat-item">
                  <text class="stat-value">{{ item.numberHouseholds || 0 }}</text>
                  <text class="stat-label">户数</text>
                </view>
                <view class="card-stat-item">
                  <text class="stat-value">{{ item.preNumber || 0 }}</text>
                  <text class="stat-label">预设户数</text>
                </view>
                <view class="card-stat-item">
                  <text class="stat-value">{{ item.difference || 0 }}</text>
                  <text class="stat-label">差值</text>
                </view>
              </view>

              <!-- 移除底部的stockPrompt显示，已移至卡片头部 -->
            </view>
          </view>
        </view>
        <wd-loadmore
          v-if="guideList.length > 0"
          custom-class="loadmore"
          :state="loadStatus"
          loading-text="努力加载中"
          finished-text="没有更多了"
        />
      </scroll-view>
    </view>

    <!-- 级联选择器 -->
    <uv-picker
      ref="areaPicker"
      :columns="areaColumns"
      :show-toolbar="true"
      title="选择区域"
      keyName="label"
      @change="onColumnChange"
      @confirm="onConfirm"
      @cancel="onCancel"
    ></uv-picker>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAreaList } from '@/api/area'
import { getGuideList } from '@/api/guide'

// 根据stockPrompt值返回对应的标签类型
function getTagType(stockPrompt) {
  const typeMap = {
    发展区: 'success',
    均衡区: 'warning',
    饱和区: 'error'
  }
  return typeMap[stockPrompt] || 'error' // 默认返回error类型
}
// 区域数据
const areaList = ref([])
const areaColumns = ref([[], []])
const selectedArea = ref('')
const selectedAreaId = ref('')

// 指南列表数据
const guideList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loadStatus = ref('loading')
const refreshing = ref(false)

// 关键字搜索
const secondaryGrid = ref('')

// 组件引用
const areaPicker = ref(null)

// 生命周期钩子
onMounted(() => {
  getAreas()
  getGuides()
})

const resetList = () => {
  selectedArea.value = ''
  pageNum.value = 1
  total.value = 0
  loadStatus.value = 'loading'
  refreshing.value = false
  guideList.value = []
  selectedArea.value = ''
  selectedAreaId.value = ''
  secondaryGrid.value = ''
  getGuides()
}

const resetKeyword = () => {
  secondaryGrid.value = ''
  loadStatus.value = 'loading'
  getGuides()
}

// 获取区域数据
async function getAreas() {
  try {
    const res = await getAreaList()
    if (res.code == '200') {
      areaList.value = res.data || []
      formatAreaColumns()
    }
  } catch (error) {
    console.error('获取区域数据失败', error)
  }
}

// 格式化区域数据为级联选择器格式
function formatAreaColumns() {
  // 找出所有父级区域
  const parentAreas = areaList.value.filter((item) => !item.parentId)

  // console.log('parentAreas', parentAreas)

  // 构建级联选择器数据
  areaColumns.value[0] = parentAreas.map((item) => ({
    label: item.areaName,
    value: item.areaId
  }))
}

// 显示选择器
function showPicker() {
  areaPicker.value.open()
}

// 选择器确认事件
function onConfirm(e) {
  const [parent, child] = e.value
  selectedArea.value = child ? `${parent.label} - ${child.label}` : parent.label
  selectedAreaId.value = child ? child.value : parent.value

  // 重置列表并重新加载数据
  pageNum.value = 1
  secondaryGrid.value = ''
  guideList.value = []
  getGuides()
}

// 选择器取消事件
function onCancel() {
  // 取消选择
}

// 选择器列变化事件
function onColumnChange(e) {
  const { columnIndex, index } = e

  // 如果是第一列变化，更新第二列数据
  if (columnIndex === 0) {
    const parentId = areaColumns.value[0][index].value
    const childAreas = areaList.value.filter((item) => item.parentId === parentId)
    const parentInfo = [
      {
        label: '',
        value: parentId
      }
    ]

    areaColumns.value[1] = parentInfo.concat(
      childAreas.map((item) => ({
        label: item.areaName,
        value: item.areaId
      }))
    )
    // console.log(areaColumns.value[1] )
  }
}

// 搜索方法
function onSearch() {
  pageNum.value = 1
  guideList.value = []
  getGuides()
}

// 获取指南列表
async function getGuides() {
  try {
    loadStatus.value = 'loading'

    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      secondaryGrid: secondaryGrid.value
      // skip: (page.value - 1) * pageSize.value
    }
    // console.log(params)

    // 如果选择了区域，添加区域筛选条件
    if (selectedAreaId.value) {
      params.areaId = selectedAreaId.value
    }

    const res = await getGuideList(params)
    if (res.code === 200) {
      const { rows, total: totalCount } = res

      if (pageNum.value === 1) {
        guideList.value = rows || []
      } else {
        guideList.value = [...guideList.value, ...rows]
      }

      total.value = totalCount || 0

      // 更新加载状态
      if (guideList.value.length >= total.value) {
        loadStatus.value = 'finished'
      } else {
        loadStatus.value = 'loading'
      }
    }
  } catch (error) {
    // console.error('获取指南列表失败', error)
    loadStatus.value = 'error'
  } finally {
    refreshing.value = false
  }
}

// 加载更多
function loadMore() {
  if (loadStatus.value !== 'loading') return

  pageNum.value++
  getGuides()
}

// 下拉刷新
function onRefresh() {
  refreshing.value = true
  pageNum.value = 1
  getGuides()
}

// 查看详情
function viewDetail(item) {
  //   uni.navigateTo({
  //     url: `/pages/guide/detail?id=${item.id}`
  //   })
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  background-color: #f0f4f8; // 更柔和的背景色
  height: 100vh;
}

.picker-area {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05); // 更柔和的阴影
  border-radius: 12rpx; // 增加圆角
  z-index: 1;
}

.search-area {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  border-radius: 12rpx;
  z-index: 1;
}

.picker-button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 80rpx;
  padding: 0 30rpx;
  border-radius: 12rpx;
  border: 1px solid #dcdcdc; // 更浅的边框色
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.icon-area {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  gap: 10rpx;
}

.scroll-view {
  height: 100%;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx; // 增加卡片之间的间距
  margin-top: 14rpx;
}

.card-item {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(60, 156, 255, 0.1); // 更明显的阴影
  transition: all 0.3s ease;
  margin: 10rpx 0rpx;
  border: 1px solid rgba(60, 156, 255, 0.15); // 更明显的边框

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(60, 156, 255, 0.15); // 更明显的按压效果
  }
}

.card-header {
  padding: 24rpx 30rpx;
  background: linear-gradient(to right, rgba(60, 156, 255, 0.05), transparent);
  border-bottom: 1px solid rgba(60, 156, 255, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.card-tag {
  display: flex;
  align-items: center;
  padding: 6rpx 20rpx;
}

.card-content {
  padding: 30rpx;
}

.card-info-section {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
}

.card-row {
  display: flex;
  margin-bottom: 20rpx;
  align-items: center;
}

.card-label {
  width: 180rpx;
  font-size: 26rpx;
  color: #666;
}

.card-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.card-divider {
  height: 1px;
  background: linear-gradient(to right, rgba(60, 156, 255, 0.1), transparent);
}

.card-stats-section {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  gap: 20rpx;
}

.card-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  padding: 16rpx;
  background-color: rgba(60, 156, 255, 0.05); // 更柔和的背景色
  border-radius: 12rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #3c9cff;
  margin-bottom: 12rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}
</style>
